package com.ruoyi.web.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.live.model.v20161101.DescribeLiveDomainConfigsRequest;
import com.aliyuncs.live.model.v20161101.DescribeLiveDomainConfigsResponse;
import com.aliyuncs.profile.DefaultProfile;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * description: 生成鉴权URL测试类
 * auth fcb
 * date 2025-07-16 14:34
 **/
public class AuthURLUtils {

    private static String md5Sum(String src) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        md5.update(StandardCharsets.UTF_8.encode(src));
        return String.format("%032x", new BigInteger(1, md5.digest()));
    }

    private static String aAuth(String uri, String key, long exp) {
//        String pattern = "^(rtmp://)?([^/?]+)(/[^?]*)?(\\\\?.*)?$";
//        Pattern r = Pattern.compile(pattern);
//        Matcher m = r.matcher(uri);
//        String scheme = "", host = "", path = "", args = "";
//        if (m.find()) {
//            scheme = m.group(1) == null ? "rtmp://" : m.group(1);
//            host = m.group(2) == null ? "" : m.group(2);
//            path = m.group(3) == null ? "/" : m.group(3);
//            args = m.group(4) == null ? "" : m.group(4);
//        } else {
//            System.out.println("NO MATCH");
//        }
        String path = uri;
        String rand = "0";  // "0" by default, other value is ok
        String uid = "0";   // "0" by default, other value is ok
        String sString = String.format("%s-%s-%s-%s-%s", path, exp, rand, uid, key);
        String hashValue = md5Sum(sString);
        String authKey = String.format("%s-%s-%s-%s", exp, rand, uid, hashValue);
//        if (args.isEmpty()) {
//            return String.format("%s%s%s%s?auth_key=%s", scheme, host, path, args, authKey);
//        } else {
//            return String.format("%s%s%s%s&auth_key=%s", scheme, host, path, args, authKey);
//        }
        return String.format("%s?auth_key=%s", path, authKey);
    }

    public static void main(String[] args) {
        // 待加密的推/播流地址，example.aliyundoc.com为推/播流域名，liveApp为AppName，liveStream为StreamName
        // 推流和播流URL采用同样的加密方法
        // AppName或StreamName不超过256字符，支持数字、大小写字母、短划线（-）、下划线（_）、等号（=）。
        String uri = "/AppName/StreamName.m3u8";
        //http://dx1test-play.shinmade.com/AppName/StreamName.flv?auth_key=1752655326-0-0-584eb4169eefcb885d24ae49fe5f6734
        // http://dx1test-play.shinmade.com/AppName/StreamName.m3u8?auth_key=1752655498-0-0-b840bf448f1ba6b3bf1bdd99250ea268
        // 鉴权Key，推流地址使用推流域名URL鉴权Key，播流地址使用播流域名URL鉴权Key
        String key = getKey();
        // exp值为UNIX时间戳，单位秒，最终失效时间由该值加上域名URL鉴权有效时长决定
        // 比如您在此处设置exp为：当前时间+3600秒，那最终失效时间为：当前时间+3600秒+域名URL鉴权有效时长。如果设置exp为：当前时间，那最终失效时间为：当前时间+域名URL鉴权有效时长
        long exp = System.currentTimeMillis() / 1000 + 1 * 3600;
        String authUri = aAuth(uri, key, exp);
        System.out.printf("URL : %s\nAuth: %s", uri, authUri);
        System.out.println();
    }

    private static String getKey() {
        DefaultProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAI5tBhbLDbrB8KeakFrPmZ", "eNyrJ62HMfWKOfheRdIdU9LU2zyFEn");
        IAcsClient client = new DefaultAcsClient(profile);
        DescribeLiveDomainConfigsRequest describeLiveDomainConfigsRequest=new DescribeLiveDomainConfigsRequest();
        describeLiveDomainConfigsRequest.setDomainName("dx1test-play.shinmade.com");
        describeLiveDomainConfigsRequest.setFunctionNames("aliauth");

        DescribeLiveDomainConfigsResponse describeLiveStreamSnapshotInfoResponse = null;
        try {
            describeLiveStreamSnapshotInfoResponse = client.getAcsResponse(describeLiveDomainConfigsRequest);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        //鉴权key
        String key="";
        for(DescribeLiveDomainConfigsResponse.DomainConfig.FunctionArg f:describeLiveStreamSnapshotInfoResponse.getDomainConfigs().get(0).getFunctionArgs()){
            if("auth_key1".equals(f.getArgName())){
                key=f.getArgValue();
            }
        }

        System.out.println(key);
        return key;
    }
}
